<?php
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------

namespace app\model;

use \think\Model;

class AgentDistribution extends Model
{
    protected $name = 'agent_distribution';
    protected $autoWriteTimestamp = false;
    protected $insert = [];
    protected $update = [];

    /**
     * 获取等级信息
     * @param int $agent_id 合作商ID
     * @param int $level 等级
     * @param int $return_radio 是否返回佣金比例
     * @return array
     */
    public static function getLevelInfo(int $agent_id, int $level, int $return_radio = 0)
    {
        $ratio = 1; //合作商分成比例
        if (!empty($agent_id)) {
            $partner = DistributionSetting::where('uuid', 'partner')->value('value');
            if ($partner) {
                $partner = json_decode($partner, true);
                $ratio   = $ratio * $partner['ratio'] / 100;
            }
            $agent = AdminAgent::field('rules')
                ->where('id', $agent_id)
                ->find();
            if (in_array(AdminAgent::RULE_CUSTOM_RATIO, $agent['rules'])) {
                $info = self::field('id, type, value')->where('agent_id', $agent_id)->find();
            } else {
                $info = DistributionSetting::field('id, type, value')->where('uuid', 'setting')->find();
            }
        } else {
            $info = DistributionSetting::field('id, type, value')->where('uuid', 'setting')->find();
        }
        $value = json_decode($info['value'], true);
        $level = $value[$level - 1];
        if (!$return_radio) {
            $res = [
                'name' => $level['name'] ?? '',
                'icon' => !empty($level['icon']) ? get_file_path($level['icon'], 1) : '',
            ];
        } else {
            $res = [
                'name'        => $level['name'] ?? '',
                'type'        => $info['type'],
                'icon'        => !empty($level['icon']) ? get_file_path($level['icon'], 1) : '',
                'ratio'       => !empty($level['ratio']) ? round($level['ratio'] * $ratio, 2) : 0,
                'ratio_one'   => !empty($level['ratio_one']) ? round($level['ratio_one'], 2) : 0,
                'agent_ratio' => $ratio,
            ];
        }
        return $res;
    }
}
